﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Utilities;
using QxFramework.Core;
using System.IO;
using UnityEngine.UI;
using System;

public class JsonDataManager : MonoSingleton<JsonDataManager>
{

    //这边放的玩家获取的金钱，
    [HideInInspector]
    public PlayerInfo GetPlayerInfo;

    private JsonData jsonData;

    [HideInInspector]
    public List<ChapterInfo> chapterInfoList;

    [HideInInspector]
    public TimeInfo GetTimeInfo;

    string ntpUrl = "http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=2";

    #region 
    //string JsonPath()
    //{
    //    return Application.streamingAssetsPath + "/LevelDataJson.json";
    //}

    //void TestJsonData()
    //{
    //    LevelInfo li1 = new LevelInfo();
    //    li1.LevelName = "1-2";
    //    li1.LevelMuiscName = "Deadlocked";
    //    li1.LevelMusicAuthor = "F-777";
    //    li1.PlayedTimes = 17;

    //    LevelInfo li2 = new LevelInfo();
    //    li2.LevelName = "1-3";
    //    li2.LevelMuiscName = "Louder";
    //    li2.LevelMusicAuthor = "NEV";
    //    li2.PlayedTimes = 19;

    //    LevelInfo li3 = new LevelInfo();
    //    li3.LevelName = "1-5";
    //    li3.LevelMuiscName = "Embers";
    //    li3.LevelMusicAuthor = "Dex Arson";
    //    li3.PlayedTimes = 19;

    //    LevelInfo li4 = new LevelInfo();
    //    li4.LevelName = "1-6";
    //    li4.LevelMuiscName = "It`s ChodeGang MotherFucker";
    //    li4.LevelMusicAuthor = "ChodeGang";
    //    li4.PlayedTimes = 19;

    //    LevelInfo li5 = new LevelInfo();
    //    li5.LevelName = "1-4";
    //    li5.LevelMuiscName = "Velocity Shift";
    //    li5.LevelMusicAuthor = "Overseer";
    //    li5.PlayedTimes = 19;

    //    LevelInfo li6 = new LevelInfo();
    //    li6.LevelName = "1-7";
    //    li6.LevelMuiscName = "1010011010";
    //    li6.LevelMusicAuthor = "Z ClaxX";
    //    li6.PlayedTimes = 19;

    //    JsonData jd = new JsonData();
    //    jd.LevelInfoList = new List<LevelInfo>();

    //    jd.LevelInfoList.Add(li1);
    //    jd.LevelInfoList.Add(li2);
    //    jd.LevelInfoList.Add(li3);
    //    jd.LevelInfoList.Add(li4);
    //    jd.LevelInfoList.Add(li5);
    //    jd.LevelInfoList.Add(li6);

    //    PlayerInfo tempPI = new PlayerInfo();
    //    tempPI.Money = 100;
    //    tempPI.UseableShapeList = new List<Shape>();
    //    tempPI.UseableShapeList.Add(Shape.BigScale);
    //    tempPI.UseableShapeList.Add(Shape.Power);
    //    tempPI.PlayableLevelList.Add("1-2");
    //    jd.playerInfo = tempPI;

    //    SaveJson(jd);
    //}

    //void SaveJson(JsonData jd)
    //{
    //    //如果本地没有对应的json 文件，重新创建
    //    if(!File.Exists(JsonPath()))
    //    {
    //        File.Create(JsonPath());
    //    }
    //    string json = JsonUtility.ToJson(jd, true);
    //    File.WriteAllText(JsonPath(), json);
    //    Debug.Log("保存成功");
    //}

    //void ReadJson()
    //{

    //    if(!File.Exists(JsonPath()))
    //    {
    //        Debug.LogError("读取的文件不存在！");
    //        return;
    //    }
    //    string json = File.ReadAllText(JsonPath());

    //    if(GetLevelInfoDic == null)
    //        GetLevelInfoDic = new Dictionary<string, LevelInfo>();

    //    GetLevelInfoDic.Clear();

    //    jsonData = new JsonData();

    //    jsonData = JsonUtility.FromJson<JsonData>(json);

    //    foreach(LevelInfo li in jsonData.LevelInfoList)
    //    {
    //        GetLevelInfoDic.Add(li.LevelName, li);
    //    }
    //    GetPlayerInfo = jsonData.playerInfo;

    //}
    #endregion

    #region 
    //void TestPlayerPrefs()
    //{
    //    LevelInfo li1 = new LevelInfo();
    //    li1.LevelName = "1-2";
    //    li1.PlayedTimes = 17;

    //    LevelInfo li2 = new LevelInfo();
    //    li2.LevelName = "1-3";
    //    li2.PlayedTimes = 19;

    //    LevelInfo li3 = new LevelInfo();
    //    li3.LevelName = "1-5";
    //    li3.PlayedTimes = 19;

    //    LevelInfo li4 = new LevelInfo();
    //    li4.LevelName = "1-6";
    //    li4.PlayedTimes = 19;

    //    LevelInfo li5 = new LevelInfo();
    //    li5.LevelName = "1-4";
    //    li5.PlayedTimes = 19;

    //    LevelInfo li6 = new LevelInfo();
    //    li6.LevelName = "1-7";
    //    li6.PlayedTimes = 19;

    //    JsonData jd = new JsonData();


    //    PlayerInfo tempPI = new PlayerInfo();
    //    tempPI.Money = 100;
    //    tempPI.UseableShapeList = new List<Shape>();
    //    tempPI.PlayableLevelList = new List<string>();
    //    //tempPI.UseableShapeList.Add(Shape.BigScale);
    //    //tempPI.UseableShapeList.Add(Shape.Power);
    //    tempPI.PlayableLevelList.Add("1-2");
    //    jd.playerInfo = tempPI;


    //    string json = JsonUtility.ToJson(jd, true);

    //    PlayerPrefs.SetString("JiuJiJson", json);
    //}
    #endregion

    //初始化
    public void CreatNewPrefs()
    {
        JsonData jd = new JsonData();
        jd.ChapterInfoList = new List<ChapterInfo>();
        //章节限制星数  章节从0开始
        var ChapterStarNeedNum = new List<int>() {0,0,6,12,30,45,70,70 };

        for (int i = 0; i < 7; i++)
        {
            var chapter = new ChapterInfo();
            chapter.ChapterName = i.ToString();
            chapter.LevelInfoList = new List<LevelInfo>();
            chapter.NeedStarNum = ChapterStarNeedNum[i];
            jd.ChapterInfoList.Add(chapter);
        }
        var allLevel = TableAgent.Instance.CollectKey1("LevelBaseInfo");
        foreach (var level in allLevel)
        {
            var levelInfo = new LevelInfo();
            levelInfo.LevelName = TableAgent.Instance.GetString("LevelBaseInfo", level, "LevelName");
            levelInfo.PlayedTimes = 0;
            levelInfo.StarNum = 0;
            string starjudgeString = TableAgent.Instance.GetString("LevelBaseInfo", level, "StarJudge");
            string[] temp = starjudgeString.Split('_');
            levelInfo.StarJudgeInfoList = new List<StarJudgeInfo>();
            foreach (var s in temp)
            {
                var starJudgeInfo = new StarJudgeInfo();
                starJudgeInfo.StarJudgeId = s;
                starJudgeInfo.isComplate = false;
                levelInfo.StarJudgeInfoList.Add(starJudgeInfo);
            }

            int chapterNumber = TableAgent.Instance.GetInt("LevelBaseInfo", level, "ChapterNumber");
            jd.ChapterInfoList[chapterNumber].LevelInfoList.Add(levelInfo);

        }

        TimeInfo tempTime = new TimeInfo();
        tempTime.getDailyRewardCount = 0;
        tempTime.isGetDailyReward = false;
        tempTime.time = "";
        jd.timeInfo = tempTime;

        //这里要加入所有的level，但目前没什么用还

        PlayerInfo tempPI = new PlayerInfo();
        tempPI.Money =10000;
        tempPI.PlayableLevelList = new List<string>();
        tempPI.UnlockedPropList = new List<int>(){};
        tempPI.EquipedPropList = new List<int>();
        //初始化属性信息
        var allAttribute = TableAgent.Instance.CollectKey1("AttributeInfo");
        tempPI.AttributeList = new List<AttributeInfo>() {};
        foreach(var att in allAttribute)
        {
            var name = TableAgent.Instance.GetString("AttributeInfo", att, "EnName");
            var arg = TableAgent.Instance.GetFloat(name + "LevelInfo", 1.ToString(), "CurrentArg");
            var tmp = new AttributeInfo(int.Parse(att),1,arg);
            tempPI.AttributeList.Add(tmp);
            Debug.Log(name + " " + arg);
        }

        tempPI.UnlockedUltList = new List<UltInfo>(){new UltInfo(1001,2)};
        tempPI.EquipedUltID = 1001;
        tempPI.PlayableLevelList.Add("1-1");
        jd.playerInfo = tempPI;
        string json = JsonUtility.ToJson(jd, true);

        PlayerPrefs.SetString("JiuJiJson", json);
        
    }
    //清空所有保存的数据 按F5
    public void DeleteAllAndCreatNew()
    {
        PlayerPrefs.DeleteAll();
        CreatNewPrefs();
        
    }

    //获取金币
    public void GetMoney(int num)
    {
        GetPlayerInfo.Money += num;
        SaveData();
    }

    //判断当前关卡是否解锁
    public bool GetLevelIsUnlocked(string levelName)
    {
        return GetPlayerInfo.PlayableLevelList.Contains(levelName);
    }

    //解锁关卡
    public void UnlockNewLevel(string levelName)
    {
        if(!GetLevelIsUnlocked(levelName))
        {
            GetPlayerInfo.PlayableLevelList.Add(levelName);
        }
        SaveData();
        
    }

    public void UnlockAllLevel()
    {
        var allLevel = TableAgent.Instance.CollectKey1("LevelBaseInfo");
        foreach (var level in allLevel)
        {

            if (level != "0-1")
                GetPlayerInfo.PlayableLevelList.Add(level);
        }

        var LevelInfo = JsonDataManager.Instance.GetLevelInfo("1-1");
        LevelInfo.StarNum = 999;
        
        SaveData();
    }

    //获取当前最新关卡
    public string GetCurLatestLevel()
    {
        
        return GetPlayerInfo.PlayableLevelList[GetPlayerInfo.PlayableLevelList.Count - 1];
    }

    public LevelInfo GetLevelInfo(string levelName)
    {
        foreach (var chapter in chapterInfoList)
        {
            foreach (var level in chapter.LevelInfoList)
            {
                if (level.LevelName.Equals(levelName))
                {
                    return level;
                }
            }

        }
        Debug.LogError("没有找到关卡信息"+levelName);
        return null;
    }

    public int GetAllStarNum()
    {
        int num = 0;
        foreach (var chapter in chapterInfoList)
        {
            foreach (var level in chapter.LevelInfoList)
            {
                num += level.StarNum;
            }

        }
        return num;
    }

    public bool ContainsUltInfo(int id)
    {
        foreach(var item in GetPlayerInfo.UnlockedUltList)
        {
            if(item.BombId == id)
            {
                return true;
            }
        }
        return false;
    }

    public int GetUltCount(int id)
    {
        foreach(var item in GetPlayerInfo.UnlockedUltList)
        {
            if(item.BombId == id)
            {
                return item.BombCount;
            }
        }
        return 0;
    }


    /// <summary>
    /// 根据字典的内容更新保存信息
    /// </summary>
    public void SaveData()
    {
        JsonData jd = new JsonData();
        jd.ChapterInfoList = chapterInfoList;
        jd.playerInfo = GetPlayerInfo;
        jd.timeInfo = GetTimeInfo;
        string json = JsonUtility.ToJson(jd, true);

        PlayerPrefs.SetString("JiuJiJson", json);
    }

    public void EquipProp( int propId )
    {
        if(GetPlayerInfo.EquipedPropList.Contains(propId))
        {
            return;
        }
        else
        {
            GetPlayerInfo.EquipedPropList.Add(propId);
        }
        SaveData();
    }

    public void UnEquipProp( int propId )
    {
        if(GetPlayerInfo.EquipedPropList.Contains(propId))
        {
            GetPlayerInfo.EquipedPropList.Remove(propId);
        }
        else
        {
            
        }
        SaveData();
    }

    public void EquipUlt(int UltId)
    {
        GetPlayerInfo.EquipedUltID = UltId;
        SaveData();
    }

    //购买道具
    public void BuyProp(int propId)
    {
        int price = TableAgent.Instance.GetInt("PropInfo", propId.ToString(), "Price");
        if (price > GetPlayerInfo.Money)
        {
            UIManager.Instance.ShowCommonMessage(new CommonMessageInfo("你的金钱不足，无法购买"));
        }
        else
        {
            GetPlayerInfo.Money -= price;
            GetPlayerInfo.UnlockedPropList.Add(propId);
        }
        SaveData();
    }

    public void BuyBomb(int bombId)
    {
        int price = TableAgent.Instance.GetInt("Ultimate", bombId.ToString(), "Price");
        if (price > GetPlayerInfo.Money)
        {
            UIManager.Instance.ShowCommonMessage(new CommonMessageInfo("你的金钱不足，无法购买"));
        }
        else
        {
            GetPlayerInfo.Money -= price;
            GetPlayerInfo.UnlockedUltList.Add(new UltInfo(bombId,2));
        }
        SaveData();
    }

    public AttributeInfo GetAttribute(int id)
    {
        foreach(var tmp in GetPlayerInfo.AttributeList)
        {
            if(tmp.AttributeId == id)
            {
                return tmp;
            }
        }
        Debug.LogError("没有找到对应属性" + id);
        return null;
    }

    public void BuyAttribute(int id)
    {
        var attribute = GetAttribute(id);
        if(attribute.isMax)
        {
            return;
        }

        var name = TableAgent.Instance.GetString("AttributeInfo", id.ToString(), "EnName");
        //var arg = TableAgent.Instance.GetFloat(name + "LevelInfo", 1.ToString(), "CurrentArg");
        var price = TableAgent.Instance.GetInt(name + "LevelInfo", attribute.CurLevel.ToString(), "NextLevelPrice");


        if(price > GetPlayerInfo.Money)
        {
            UIManager.Instance.ShowCommonMessage(new CommonMessageInfo("你的金钱不足，无法购买"));
        }
        else
        {
            GetPlayerInfo.Money -= price;
            attribute.CurLevel += 1;
            attribute.CurArg = TableAgent.Instance.GetFloat(name + "LevelInfo", attribute.CurLevel.ToString(), "CurrentArg");
            attribute.isMax = TableAgent.Instance.GetInt(name + "LevelInfo", attribute.CurLevel.ToString(), "IsMaxLevel") == 1;
        }

        SaveData();
    }


    void ReadProjectJson()
    {
        if(!PlayerPrefs.HasKey("ProjectJson"))
            CreatNewPrefs();

        string json = PlayerPrefs.GetString("ProjectJson");

        jsonData = new JsonData();

        jsonData = JsonUtility.FromJson<JsonData>(json);

        chapterInfoList = jsonData.ChapterInfoList;
        GetPlayerInfo = jsonData.playerInfo;
        GetTimeInfo = jsonData.timeInfo;
    }

    public void OnAwake()
    {
        //TestPlayerPrefs();
        //PlayerPrefs.DeleteAll();
        ReadProjectJson();
        StartCoroutine(GetTime());
    }

    IEnumerator GetTime()
    {
        string tmpStr = "";
        //Debug.Log(System.DateTime.Today.ToString());
        WWW www = new WWW(ntpUrl);
        yield return www;
        //today = DateTime.Parse(www.text);
        if (www.text == "" || www.text.Trim() == "")//为空时使用本地时间
        {

            tmpStr = System.DateTime.Now.Year + "_" + System.DateTime.Now.Month + "_" + System.DateTime.Now.Day;
            Debug.Log(tmpStr);

        }
        else//网络时间获取成功
        {
            string timeStr = www.text.Substring(2);
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddMilliseconds(Convert.ToDouble(timeStr));
            timeStr = time.ToString();


            tmpStr = time.Year + "_" + time.Month + "_" + time.Day;
            Debug.Log(tmpStr);
        }

        if(tmpStr != (GetTimeInfo.time))
        {
            GetTimeInfo.isGetDailyReward = false;
            GetTimeInfo.time = tmpStr;
        }

        SaveData();
    }


    //获取每日奖励的数据库相关操作
    public void GetDailyReward()
    {
        GetTimeInfo.isGetDailyReward = true;
        GetTimeInfo.getDailyRewardCount++;
        SaveData();
    }

    public void ResetDailyReward()
    {
        GetTimeInfo.getDailyRewardCount = 0;
        SaveData();
    }

    void Update ()
    {
	    
	}
}
